package chap_05;

import org.junit.jupiter.api.Test;

import java.util.Arrays;
import java.util.function.IntSupplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * 构建流
 */
public class Run_07 {
    /**
     * 由值创建流
     */
    @Test
    public void demo_01() {
        Stream<String> stream = Stream.of("Java 8 ", "Lambdas ", "In ", "Action");
        stream.map(String::toUpperCase).forEach(System.out::println);
    }

    /**
     * 由数组创建流
     */
    @Test
    public void demo_02() {
        int[] numbers = {2, 3, 5, 7, 11, 13};
        int sum = Arrays.stream(numbers).sum();
        System.out.println(sum);
    }

    /**
     * 由函数生成流：创建无限流
     */
    @Test
    public void demo_03() {
        Stream.iterate(0, n -> n + 2)
                .limit(10)
                .forEach(System.out::println);
    }

    /**
     * 斐波纳契元组序列
     */
    @Test
    public void demo_04() {
        Stream.iterate(new int[]{0, 1},
                t -> new int[]{t[1], t[0]+t[1]})
                .limit(20)
                .forEach(t -> System.out.println("(" + t[0] + "," + t[1] +")"));
    }

    /**
     * 生成
     */
    @Test
    public void demo_05() {
        Stream.generate(() -> 1)
                .limit(5)
                .collect(Collectors.toList())
                .forEach(System.out::println);
    }

    /**
     *
     */
    @Test
    public void demo_06() {
        Stream.generate(Math::random)
                .limit(5)
                .collect(Collectors.toList())
                .forEach(System.out::println);
    }

    /**
     *
     */
    @Test
    public void demo_07() {
        IntSupplier fib = new IntSupplier(){
            private int previous = 0;
            private int current = 1;
            @Override
            public int getAsInt(){
                int oldPrevious = this.previous;
                int nextValue = this.previous + this.current;
                this.previous = this.current;
                this.current = nextValue;
                return oldPrevious;
            }
        };
        IntStream.generate(fib).limit(10).forEach(System.out::println);
    }
}
